//
//  UIUtils.m
//  WXTime
//
//  Created by wei.chen on 12-7-22.
//  Copyright (c) 2012年 www.iphonetrain.com 无限互联ios开发培训中心 All rights reserved.
//

#import "Utils.h"
#import "RSADataSigner.h"
#import <CommonCrypto/CommonDigest.h>

@implementation Utils

+(NSString *)imgPath: (NSString *)path{
    
    return [[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: allConstDocPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"Contents/Resources/%@",path]];
}

+ (NSString *)getDocumentsPath:(NSString *)fileName {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documents = [paths objectAtIndex:0];
    NSString *path = [documents stringByAppendingPathComponent:fileName];
    
    return path;
}

+ (NSString*) stringFromFomate:(NSDate*) date formate:(NSString*)formate {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:formate];
	NSString *str = [formatter stringFromDate:date];
	return str;
}

+ (NSDate *) dateFromFomate:(NSString *)datestring formate:(NSString*)formate {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formate];
    NSDate *date = [formatter dateFromString:datestring];
    return date;
}


//Sat Jan 12 11:50:16 +0800 2013
+ (NSString *)fomateString:(NSString *)datestring {
    NSString *formate = @"E MMM d HH:mm:ss Z yyyy";
    NSDate *createDate = [Utils dateFromFomate:datestring formate:formate];
    NSString *text = [Utils stringFromFomate:createDate formate:@"MM-dd HH:mm"];
    return text;
}

+(float)OSVersion
{
    return [[[UIDevice currentDevice] systemVersion] floatValue];
}

// 获取字符串高度
+ (float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    //ios7.0前
//    CGSize sizeToFit = [value sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
    
    //ios7
    CGSize detailsLabSize = CGSizeMake(width, MAXFLOAT);
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    CGSize sizeToFit = [value boundingRectWithSize:detailsLabSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil].size;
    
    return sizeToFit.height;
}

//获取字符串宽度
+ (float)widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height
{
    //ios7
    CGSize detailsLabSize = CGSizeMake(MAXFLOAT, height);
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    CGSize sizeToFit = [value boundingRectWithSize:detailsLabSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil].size;
    
    return sizeToFit.width;
}

// 指定字符串变色
+(void)fuwenbenLabel:(UILabel *)labell FontNumber:(id)font AndRange:(NSRange)range AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:labell.text];
    
    //设置字号
    [str addAttribute:NSFontAttributeName value:font range:range];

    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    
    labell.attributedText = str;
}

+ (NSString *)md5:(NSString *)str
{
    const char *original_str = [str UTF8String];
    
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(original_str, strlen(original_str), result);
    
    NSMutableString *hash = [NSMutableString string];
    
    for (int i = 0; i < 16; i++)
        
        [hash appendFormat:@"%02X", result[i]];
    
    return [hash lowercaseString];
    
}

//返回当前时间的时间戳
+ (NSString *)getCurrentDateStamp
{
    NSDate *date = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return timeSp;
}

//返回指定时间13位时间戳
+ (NSString *)dateStampWithDate:(NSDate *)date
{
    NSString *timeSp = [NSString stringWithFormat:@"%ld000", (long)[date timeIntervalSince1970]];
    return timeSp;
}

//图片截取
+ (UIImage*) crop:(UIImage*)theImage{
    // Get size of current image
    CGSize size = [theImage size];
    
    // Create rectangle that represents a cropped image
    CGFloat desiredRatio = 1;
    
    CGFloat croppedWidth = 0.0;
    CGFloat croppedHeight = 0.0;
    
    CGRect rect;
    
    if (size.height/size.width >= desiredRatio) {
        croppedWidth = size.width;
        croppedHeight = size.width * desiredRatio;
        CGFloat difference = (size.height-croppedHeight)/2;
        rect = CGRectMake(0.0, difference ,croppedWidth, croppedHeight);
    }
    else{
        return theImage;
    }
    
    // Create bitmap image from original image data,
    // using rectangle to specify desired crop area
    CGImageRef imageRef = CGImageCreateWithImageInRect([theImage CGImage], rect);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return croppedImage;
}

+(NSString *)compareCurrentTime:(NSDate*) compareDate
{
    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小前",temp];
    }
    else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }
    else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    return  result;
}

// 正则表达式
+ (BOOL)checkContent:(NSString *)content regex:(NSString *)regex
{
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:content];
}

+ (NSString *)encodeBase64String:(NSString*)input
{
    NSData *originData = [input dataUsingEncoding:NSASCIIStringEncoding];
    NSString *encodeResult = [originData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    return encodeResult;
}

+ (NSString *)decodeBase64String:(NSString*)input
{
    NSData *decodeData = [[NSData alloc] initWithBase64EncodedString:input options:0];
    NSString *decodeStr = [[NSString alloc] initWithData:decodeData encoding:NSASCIIStringEncoding];
    return decodeStr;
}

+ (NSString*)encodeBase64Data:(NSData*)data
{
    NSString *encodeResult = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    return encodeResult;
}

+ (NSString*)decodeBase64Data:(NSData*)data
{
    NSString *decodeStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    return decodeStr;
}

//

+ (NSString *)generateURL:(NSString*)baseURL params:(NSDictionary*)params
{
    if (params) {
        
        NSMutableArray* pairs = [NSMutableArray array];
        for (NSString* key in params.keyEnumerator) {
            
            NSString* value = [params objectForKey:key];
            value = [value isKindOfClass:[NSString class]] ? value:[NSString stringWithFormat:@"%@", value];
            CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
            (NULL, /* allocator */
             (CFStringRef)value,
             NULL, /* charactersToLeaveUnescaped */
             (CFStringRef)@"!*'();:@&=+$,/?%#[]",
             kCFStringEncodingUTF8));
            
            [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, value]];
        }
        
        NSString* query = [pairs componentsJoinedByString:@"&"];
        NSRange rang = [baseURL rangeOfString:@"?"];
        NSString* url = @"";
        if(rang.length >0){
            url = [NSString stringWithFormat:@"%@&%@", baseURL, query];
        }else{
            
            url = [NSString stringWithFormat:@"%@?%@", baseURL, query];
        }
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        return url;
        
    } else {
        return baseURL;
    }
}

// 唯一标识
+ (NSString*)UUID
{
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

// 获取设备型号
+ (NSString *)deviceModel
{
    return [UIDevice currentDevice].model;
}

// 获取pp版本
+ (NSString *)appVersion
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    CFShow((__bridge CFTypeRef)(infoDictionary));
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}

// 时间戳转时间
+ (NSDate *)dateFromTimestamp:(NSNumber *)timestamp
{
    if ((!timestamp) || (![timestamp isKindOfClass:[NSNumber class]])) {
        return nil;
    }
    
    NSString *timestampString = [NSString stringWithFormat:@"%@", timestamp];
    if (timestampString.length > 11) {
        timestampString = [timestampString substringToIndex:10];
    }
    
    NSTimeInterval time = [timestampString doubleValue];
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:time];
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate:date];
//    date = [date dateByAddingTimeInterval:interval];
    
    return date;
}

+ (NSString *)dateStringWithTimestamp:(NSNumber *)Timestamp
{
    NSDate *docDate = [Utils dateFromTimestamp:Timestamp];
    NSString *dateString = [Utils stringFromFomate:docDate formate:@"yyyy-MM-dd"];
    return dateString;
}

+ (void)callPhone:(NSString *)phone viewController:(UIViewController *)vc
{
    if ([NSString isNullOrEmpty:phone] || (!vc)) {
        return;
    }
    
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@", phone];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [vc.view addSubview:callWebview];
}
+ (CGFloat)iphone6AutoScaleW:(CGFloat)w{
    
    return w * (SCREEN_WIDTH / 375.0f);
    
}

+ (CGFloat)iphone6AutoScaleH:(CGFloat)h{
    return h * (SCREEN_HEIGHT / 590.0f);
    
}

+ (CGFloat)iphone5AutoScaleW:(CGFloat)w{
    
    return w * (SCREEN_WIDTH / 320.0f);
    
}

// 获取网络时间
+ (NSDate *)getInternetDate
{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    return localeDate;
}

/**
 *  根据图片url获取图片尺寸
 */
+ (CGSize)getImageSizeWithURL:(id)URL{
    NSURL * url = nil;
    if ([URL isKindOfClass:[NSURL class]]) {
        url = URL;
    }
    if ([URL isKindOfClass:[NSString class]]) {
        url = [NSURL URLWithString:URL];
    }
    if (!URL) {
        return CGSizeZero;
    }
    CGImageSourceRef imageSourceRef =     CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    CGFloat width = 0, height = 0;
    if (imageSourceRef) {
        CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);
        if (imageProperties != NULL) {
            CFNumberRef widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
            if (widthNumberRef != NULL) {
                CFNumberGetValue(widthNumberRef, kCFNumberFloat64Type, &width);
            }
            CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
            if (heightNumberRef != NULL) {
                CFNumberGetValue(heightNumberRef, kCFNumberFloat64Type, &height);
            }
            CFRelease(imageProperties);
        }
        CFRelease(imageSourceRef);
    }
    return CGSizeMake(width, height);
}

//经纬度计算
+(double)distanceBetweenOrderBy:(double) lat1 :(double) lat2 :(double) lng1 :(double) lng2{
    
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
    
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
    
    double  distance  = [curLocation distanceFromLocation:otherLocation];
    
    return  distance;
    
}

// 比较时间
+ (int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"oneDay : %@, anotherDay : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //在指定时间前面 过了指定时间 过期
        NSLog(@"oneDay  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //没过指定时间 没过期
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //刚好时间一样.
    //NSLog(@"Both dates are the same");
    return 0;
    
}
// 时间戳转nsdate
+(NSDate *)Get_timeForDate:(NSString *)dateStr{
    
    NSString *str=dateStr;//时间戳
    NSTimeInterval time=[str doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    NSLog(@"date:%@",[detaildate description]);
    return detaildate;
}
// 时间转换
+(NSString *)get_time:(NSString *)dateStr{
    
    NSTimeInterval time=[dateStr integerValue];//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    
    return currentDateStr;
}

+ (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7横屏
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    // 判断前缀
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R、G、B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

@end
